
from PyQt5.QtCore import QObject, pyqtSignal, QTimer


class AlertManager(QObject):
    alert_triggered = pyqtSignal(str, str)  # level, message

    def __init__(self, parent=None):
        super().__init__(parent)
        self._setup_alert_system()

    def _setup_alert_system(self):
        self.alert_timer = QTimer()
        self.alert_timer.timeout.connect(self.check_resources)
        self.alert_timer.start(5000)  # 5秒检查一次

    def check_resources(self):
        """统一资源检查入口"""
        try:
            import psutil
            cpu = psutil.cpu_percent()
            mem = psutil.virtual_memory().percent
            if cpu > 90 or mem > 90:
                self.trigger_alert('critical', f'资源使用过高 CPU:{cpu}% MEM:{mem}%')
        except ImportError:
            self.trigger_alert('warning', 'psutil未安装，资源监控不可用')

    def trigger_alert(self, level, message):
        """触发警报"""
        self.alert_triggered.emit(level, message)